<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <!-- 表单enctype属性值为multipart/form-data -->
  <form action="post" enctype="multipart/form-data">
    <input type="file" name="upload_file" id="upload_file">
    <hr />
    <input type="button" name="upload" id="upload" value="上传">
  </form>
  <progress max="100" value="0"></progress>
  <div id="v_scale"></div>

  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script>

    /********** 这里php测试的端口使用的是82端口，可以自行更改 ***********/

    let file = document.getElementById("upload_file"); // 这里使用原生监听属性，监听上传文件input表单
    let $upload = $("#upload"); // 监听上传按钮
    let $progress = $("progress"); // 监听进度条
    let $vScale = $("#v_scale"); // 显示进度比例

    $upload.click(() => {
      let fd = new FormData(); // 创建FormData对象
      fd.append("upload_file", file.files[0]); // 添加数据
      $.ajax({
        url: "http://127.0.0.1:82/file_upload.php", 
        type: 'post', 
        data: fd, // fd对象
        xhr() { // 此方法，用创建XMLHttpRequest对象的回调，jq以做兼容
          let xhr = $.ajaxSettings.xhr();
          let scale = 0;
          xhr.upload.addEventListener("progress", event => {
            if (event.lengthComputable) {
              scale = Math.round(event.loaded / event.total * 100);
              $progress.val(scale);
              $vScale.html(scale + "%");
            }
          });
          return xhr;          
        },
        processData: false,
        contentType: false,
        success(res) {
          $vScale.html($vScale.html() + ("——" + res));
        },
        error(err) {
          $vScale.text() += ("——上传失败");
          console.log(err.status)
        }
      })
    });

  </script>
</body>

</html>